package io.youngking.modules.feedback.controller;

import java.text.SimpleDateFormat;
import java.util.*;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.toolkit.StringUtils;
import io.youngking.modules.wxuserinfo.entity.WxuserinfoEntity;
import io.youngking.modules.wxuserinfo.service.WxuserinfoService;
import io.youngking.weixin4j.Weixin;
import io.youngking.weixin4j.WeixinException;
import io.youngking.weixin4j.model.message.template.TemplateData;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import io.youngking.modules.feedback.entity.FeedbackEntity;
import io.youngking.modules.feedback.service.FeedbackService;
import io.youngking.common.utils.PageUtils;
import io.youngking.common.utils.R;


/**
 * 用户建议表
 *
 * @author limouren
 * @email sunlightcs@gmail.com
 * @date 2018-07-27 10:53:59
 */
@RestController
@RequestMapping("feedback/feedback")
public class FeedbackController {
    @Autowired
    private FeedbackService feedbackService;
    @Autowired
    private WxuserinfoService wxuserinfoService;

    /**
     * 列表
     */
    @RequestMapping("/list")
    @RequiresPermissions("feedback:feedback:list")
    public R list(@RequestParam Map<String, Object> params) {
        int currPage = 0;
        int limit = 0;

        Map<String, Object> map = new HashMap<>();
        //分页参数
        if (params.get("page") != null) {
            currPage = Integer.parseInt((String) params.get("page"));
        }
        if (params.get("limit") != null) {
            limit = Integer.parseInt((String) params.get("limit"));
        }
        map.put("key", params.get("key"));
        map.put("offset", (currPage - 1) * limit);
        map.put("limit", limit);

        //获取数据
        List<Map<String, Object>> list = feedbackService.getlist(map);
        Map<String, Object> params1 = new HashMap<>();
        params1.put("list", list);
        params1.put("CurrPage", currPage);
        params1.put("PageSize", limit);
        params1.put("TotalCount", list.size());
        params1.put("TotalPage", (int) Math.ceil((double) list.size() / limit));

        PageUtils page = feedbackService.Pagelist(params1);

        return R.ok().put("page", page);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
    @RequiresPermissions("feedback:feedback:info")
    public R info(@PathVariable("id") Integer id) {
        Map<String, Object> map = feedbackService.getinfo(id);
        String img = map.get("imgurl").toString();
        String newlist = "";
        if (StringUtils.isNotEmpty(img)) {
            String[] imglist = img.split(",");
            for (int j = 0; j < imglist.length; j++) {
                String fileSavePath = "http://www.yanzuohotel.com/shenglian-fast/static/feedback/" + imglist[j];
                newlist += fileSavePath + ",";
            }
        }
        if (org.apache.commons.lang.StringUtils.isNotEmpty(newlist)) {
            newlist = newlist.substring(0, newlist.length() - 1);
        }
        map.put("imgurl", newlist);
        return R.ok().put("feedback", map);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    @RequiresPermissions("feedback:feedback:save")
    public R save(@RequestBody FeedbackEntity feedback) {
        feedbackService.insert(feedback);

        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    @RequiresPermissions("feedback:feedback:update")
    public R update(@RequestBody FeedbackEntity feedback) throws WeixinException {
        feedback.setStatus(1);
        feedback.setReplytime(new Date());
        feedbackService.updateById(feedback);
        //微信发送给用户
        FeedbackEntity feedbackEntity = feedbackService.selectById(feedback.getId());
        WxuserinfoEntity wxuserinfoEntity = wxuserinfoService.selectById(new EntityWrapper<WxuserinfoEntity>().eq("id", feedbackEntity.getCustomerid()).eq("subscribe", 1));
        Weixin weixin = new Weixin();
        if (StringUtils.isNotEmpty(wxuserinfoEntity.getOpenid())) {
            List<TemplateData> templateDataList = new ArrayList<>();
            TemplateData templateData = new TemplateData();
            templateData.setColor("red");
            templateData.setValue("商家回复：" + feedback.getReplycontent());
            templateData.setKey("first");
            templateDataList.add(templateData);
            TemplateData templateData1 = new TemplateData();
            templateData1.setColor("");
            templateData1.setValue(wxuserinfoEntity.getNickname());
            templateData1.setKey("keyword1");
            templateDataList.add(templateData1);
            TemplateData templateData2 = new TemplateData();
            templateData2.setColor("");
            templateData2.setValue(feedback.getContents());
            templateData2.setKey("keyword2");
            templateDataList.add(templateData2);
            TemplateData templateData3 = new TemplateData();
            templateData3.setColor("");
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");//设置日期格式
            String audittime = df.format(new Date());
            templateData3.setValue(audittime);
            templateData3.setKey("keyword3");
            templateDataList.add(templateData3);
            TemplateData templateData4 = new TemplateData();
            templateData4.setColor("");
            templateData4.setValue("感谢您反馈，我们会慎重考虑您的建议。祝您生活愉快!");
            templateData4.setKey("remark");
            templateDataList.add(templateData4);
            weixin.message().sendTemplateMessage(wxuserinfoEntity.getOpenid(), "lPE0-885aInE0_MVKR2qgV6TrMqjX7EhLCVexauJE3s", templateDataList, "http://www.yanzuohotel.com/dpfeedback?id=" + feedbackEntity.getId() + "&wxuserinfoid=" + wxuserinfoEntity.getId());
        }
        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    @RequiresPermissions("feedback:feedback:delete")
    public R delete(@RequestBody Integer[] ids) {

        feedbackService.deleteBatchIds(Arrays.asList(ids));

        return R.ok();
    }

}
